<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午11:25
 */

namespace app\index\controller;


use Alipay\Alipayobj;
use app\common\controller\ActionLogs;
use app\common\controller\CardPut;
use app\common\controller\Ekaipiao;
use app\common\controller\Platurl;
use app\common\controller\Pub;
use app\common\model\Agent;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\CardUserUpdate;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\MerchantCashier;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\PayTplSend;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Cache;
use think\Controller;
use Wechat\Wxobjopen;
use Think\Cookie;

class Wxauth extends Controller
{

    public function index()
    {

        return $this->fetch();
    }

    public function aliauth()
    {

        $map['id'] = request()->param('merchid');
        $User = new Momerchant();
        $Agent = new Agent();
        $users = $User->where($map)->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $datas['app_id'] = $agent['ali_app_id'];
        $datas['method'] = "alipay.open.auth.token.app";
        $datas['charset'] = "UTF-8";
        $datas['sign_type'] = "RSA2";
        $datas['timestamp'] = date('Y-m-d H:i:s');
        $datas['version'] = "1.0";
        $biz_content['grant_type'] = "authorization_code";
        $biz_content['code'] = request()->param('app_auth_code');
        $datas['biz_content'] = json_encode($biz_content);
        $signContent = $aliObj->rsaSign($datas, $signType = "RSA2");

        $datas['sign'] = $signContent;
        $sj = $aliObj->scanpay($datas);
        $sdata = json_decode($sj, true);

        if ($sdata['alipay_open_auth_token_app_response']['code'] == "10000") {
            $sali_merid = $sdata['alipay_open_auth_token_app_response']['app_auth_token'];
            $data['ali_merid'] = $sali_merid;
            $Momerchant = new Momerchant();
            $up = $Momerchant->save($data, $map);
            if ($up) {
                $this->success('绑定成功');
            } else {
                $this->error('绑定失败');
            }
        } else {
            $this->error('绑定失败,请联系系统管理员');
        }


    }

    public function aliauthmach()
    {
        $map['id'] = request()->param('merchid');
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where($map)->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $datas['app_id'] = $agent['ali_app_id'];
        $datas['method'] = "alipay.open.auth.token.app";
        $datas['charset'] = "UTF-8";
        $datas['sign_type'] = "RSA2";
        $datas['timestamp'] = date('Y-m-d H:i:s');
        $datas['version'] = "1.0";
        $biz_content['grant_type'] = "authorization_code";
        $biz_content['code'] = request()->param('app_auth_code');
        $datas['biz_content'] = json_encode($biz_content);
        $signContent = $aliObj->rsaSign($datas, $signType = "RSA2");
        $datas['sign'] = $signContent;
        $sj = $aliObj->scanpay($datas);
        $sdata = json_decode($sj, true);
        if ($sdata['alipay_open_auth_token_app_response']['code'] == "10000") {
            $sali_merid = $sdata['alipay_open_auth_token_app_response']['app_auth_token'];
            $data['ali_merid'] = $sali_merid;
            $Merchant = new Merchant();
            $up = $Merchant->save($data, $map);
            if ($up) {
                $this->success('绑定成功');
            } else {
                $this->error('绑定失败');
            }
        } else {
            $this->error('绑定失败,请联系系统管理员');
        }
    }
//
//获取授权
    public function auth()
    {

        $request = request();
        $System = new System();
        $config = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],

        );;
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();

        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("Wxauth/Auth", $_GET);
            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {

            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $data['authorizer_appid'] = $appinfo['authorization_info']['authorizer_appid'];
            $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
            $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
            $data['at_addtime'] = time();
            $data['at_expires_in'] = 7000;
            $data['addtime'] = time();
            $data['zt'] = 1;
            $func_info = "";
            foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                $func_info .= $v['funcscope_category']['id'] . ',';
            }
            $WxOpen = new WxOpen();
            $data['func_info'] = $func_info;
            $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();
            if ($wx_open) {
                $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
            } else {
                $sj = $WxOpen->save($data);
            }
            if ($sj) {
                $this->success('授权成功', url('Wxauth/index'));
            } else {
                $this->error('授权失败');
            }

        }
    }

//开放平台ticket接收
    public function ticket()
    {
        $id = request()->param('id');
        trace( "notify_ticket1" . json_encode($id,256),'SysRunNotifyLog');
        $Agent = new Agent();
        $config = $Agent->where(array('id' => $id))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
        );
        trace( "notify_ticket2" . json_encode($options,256),'SysRunNotifyLog');
        $weObj = new Wxobjopen($options);
        $info = $weObj->valid();
        $xml_to_array = $weObj->xml_to_array();
        if ($xml_to_array['InfoType'] == "component_verify_ticket") {
            $ticket = $xml_to_array['ComponentVerifyTicket'] ? $xml_to_array['ComponentVerifyTicket'] : 'error';
            $Agent->save(array('open_ticket' => $ticket, 'ticket_time' => time()), ['component_appid' => $xml_to_array['AppId']]);
            die("success");


        } elseif ($xml_to_array['InfoType'] == "authorized") {
            die("success");
        } else {
            die("success");
        }
    }

    //开放平台微信事件接收
    public function event()
    {
        try{
        $ActionLogs = new ActionLogs();
        $postStr = file_get_contents('php://input');
        if (!empty($postStr)) {
            //微信支付事件接收
            $ActionLogs->writelog("payos", "wxauth", "event/wxpaynotify", "接收推送信息:", $postStr);
            libxml_disable_entity_loader(true);
            $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);


            if (isset($msg['return_code'])) {

                $pay_zt = $msg['return_code'];
                if ($pay_zt == "SUCCESS") {
                    $Paylog = new Paylog();
                    $data['pay_statu'] = 1;
                    $payinfo = $Paylog->where(['orderid' => $msg['out_trade_no']])->field('orderid,tzzt,mid')->find();
                    $ActionLogs->writelog("payos", "wxauth", "event/wxpaynotifydata", "支付推送信息-1:", $payinfo);
                    $ActionLogs->writelog("payos", "wxauth", "event/wxpaynotifydata", "支付推送信息-2:", $msg);
                    if ((int)$payinfo['tzzt'] == 0) {

                        action('Wxpay/order_query', array($msg['out_trade_no']));
                        $Pub = new Pub();
                        $Pub->sendnotify($payinfo['mid'], $postStr);
                    }
                    $su = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    echo $su;
//                    } elseif ($payinfo['tzzt'] == 1) {
//
//                    }
                }

            }


            //开放平台全网发布验证
            $request = request();
            if ($request->param('appid') == "wx570bc396a51b8ff8") {
                $Agent = new Agent();
                $config = $Agent->where(array('id' => request()->param('id')))->find();
                $options = array(
                    'component_token' => $config['component_token'], // 填写你设定的key
                    'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                    'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
                    'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
                    'open_ticket' => $config['open_ticket'],
                    'authorizer_appid' => "wx570bc396a51b8ff8",
                    'authorizer_refresh_token' => '',

                );
                $weObj = new Wxobjopen($options);
                $type = $weObj->getRev()->getRevType();
                $user = $weObj->getRevFrom();
                switch ($type) {

                    case 'event':

                        $eventype = $weObj->getRev()->getRevEvent();

                        $weObj->text($eventype['event'] . "from_callback")->reply();

                        exit;
                        break;
                    case "text":
                        $eventype = $weObj->getRev()->getRevContent();

                        if ($eventype == "TESTCOMPONENT_MSG_TYPE_TEXT") {
                            $weObj->text("TESTCOMPONENT_MSG_TYPE_TEXT_callback")->reply();

                        } else {
                            // * 发送客服消息
                            // * @param array $data 消息结构{"touser":"OPENID","msgtype":"news","news":{...}}
                            $weObj->text("")->reply();
                            $QUERY_AUTH_CODE = explode(":", $eventype);
                            $appinfo = $weObj->authorization_info($QUERY_AUTH_CODE[1]);
                            $datas['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                            $datas['at_expires_in'] = 7000;
                            $datas['at_addtime'] = time();
                            $WxOpen = new WxOpen();
                            $WxOpen->save($datas, ['authorizer_appid' => 'wx570bc396a51b8ff8']);
                            $da['touser'] = $user;
                            $da['msgtype'] = 'text';
                            $da['text'] = array(
                                'content' => $QUERY_AUTH_CODE[1] . "_from_api",
                            );
                            $sss = $weObj->sendCustomMessage($da);

                        }
                        break;
                        exit();

                }
                exit();
            }
            //全网发布验证结束
            $WxOpen = new WxOpen();
            $Agent = new Agent();
            $config = $Agent->where(array('id' => request()->param('id')))->find();
            $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
            $options = array(
                'component_token' => $config['component_token'], // 填写你设定的key
                'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
                'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
                'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
                'open_ticket' => $config['open_ticket'],
                'authorizer_appid' => $users['authorizer_appid'],
                'authorizer_refresh_token' => $users['authorizer_refresh_token'],

            );

            $weObj = new Wxobjopen($options);
            $weObj->valid();
            $type = $weObj->getRev()->getRevType();
            $alldata = $weObj->getRev()->getRevData();
            $ActionLogs->writelog("payos", "wxauth", "event/" . $type, "接收推送信息:", $alldata);
            //处理重复推送问题
            if (isset($alldata['MsgID'])) {
                $msgid = Cache::get($alldata['MsgID']);
                if ($msgid) {
                    die("SUCCESS");
                } else {
                    Cache::set($alldata['MsgID'], json_encode($alldata), 3600);
                }
            } elseif (isset($alldata['FromUserName']) && isset($alldata['CreateTime'])) {
                if (!isset($alldata['UserCardCode'])) {
                    $stk = Cache::get($alldata['FromUserName'] . $alldata['CreateTime']);
                    if ($stk) {
                        die("SUCCESS");
                    } else {
                        Cache::set($alldata['FromUserName'] . $alldata['CreateTime'], json_encode($alldata), 3600);
                    }
                }
            }

            $ActionLogs->writelog("payos", "wxauth", "event/type" . $type, "1:", $type);
            switch ($type) {
                case 'text':
                    //关键词回复
                    $pushdata = $weObj->getRev()->getRevData();
                    $datas['gh_id'] = $pushdata['ToUserName'];
                    $datas['openid'] = $pushdata['FromUserName'];
                    $datas['msg_key'] = $pushdata['Content'];
                    $CardPut = new CardPut();
                    $newsdata = $CardPut->replymsgputcard($datas);
                    if (is_array($newsdata)) {
                        $res = $weObj->news($newsdata)->reply();
                    } else {
                        $weObj->transfer_customer_service()->reply();
                    }

                    break;
                case "event":
//                    $ActionLogs->writelog("payos", "wxauth", "event", "event-0:", $alldata);
                    $eventype = $weObj->getRev()->getRevEvent();
//                    $ActionLogs->writelog("payos", "wxauth", "event", "event-0-1:", $eventype);
                    if ($eventype['event'] == "CLICK") {
                        if ($eventype['key'] == "tel") {
                            $weObj->getRev()->text('客服热线:400-0372-203')->reply();
                        } else {
                            $pushdata = $weObj->getRev()->getRevData();
                            $datas['gh_id'] = $pushdata['ToUserName'];
                            $datas['openid'] = $pushdata['FromUserName'];
                            $datas['click_key'] = $pushdata['EventKey'];
                            $CardPut = new CardPut();
                            $newsdata = $CardPut->clickmenuputcard($datas);
                            if (is_array($newsdata)) {
                                $res = $weObj->news($newsdata)->reply();
                            } else {
                                echo 'SUCCESS';

                            }
                        }

                    } elseif ($eventype['event'] == "user_authorize_invoice") {
                        //电子发票事件
                        $pushdata = $weObj->getRev()->getRevData();
                        $Ekaipiao = new Ekaipiao();
                        $a = $Ekaipiao->save_fp($pushdata);
                    }
//                //子商户审核
//                if ($eventype['event'] == "card_merchant_check_result") {
//                    $mal['merchant_id'] = $eventype['MerchantId'];
//                    $datas['ispass'] = $eventype['IsPass'];
//                    $datas['reason'] = $eventype['Reason'];
//                    $datas['statu'] = $eventype['IsPass'];
//                    $up = M('card')->where($mal)->save($datas);

//                    exit();
//
//                }
                    //关注事件
                    if ($eventype['event'] == "subscribe") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['createtime'] = $pushdata['CreateTime'];
                        $datas['openid'] = !empty($pushdata['FromUserName'])?$pushdata['FromUserName']:"";
                        $res = action('Wxcard/getfansinfo', array($datas));

                        $CardPut = new CardPut();
                        $newsdata = $CardPut->followcardput($datas);
                        if (is_array($newsdata)) {
                            $res = $weObj->news($newsdata)->reply();
                        }
                        //关注送券 END
                        $notgetnewsdata = $CardPut->sendcardsnotice($datas);
                        $ActionLogs->writelog("payos", "wxauth", "event", "sendcardsnotice-1:", $notgetnewsdata);
                        if (is_array($notgetnewsdata)) {
                            $ress = $weObj->news($notgetnewsdata)->reply();
                            $ActionLogs->writelog("payos", "wxauth", "event", "sendcardsnotice-2:", $ress);

                        }
                        //关注通知 END
//                        if ($pushdata['EventKey']=="qrscene_123456") {
//                            $weObj->getRev()->text("一号展厅" . "开锁成功")->reply();
//                        }

//
                    }
//                    if ($eventype['event'] == "SCAN") {
//                        $pushdata = $weObj->getRev()->getRevData();
//                        if ($pushdata['EventKey'] == "123456") {
//                            $weObj->getRev()->text("一号展厅" . "开锁成功")->reply();
//                        }
//
//                    }

                    //取关事件
                    if ($eventype['event'] == "unsubscribe") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['createtime'] = $pushdata['CreateTime'];
                        $datas['openid'] = empty($pushdata['FromUserName'])?$pushdata['FromUserName']:"";
                        $res = action('Wxcard/offfansinfo', array($datas));
                    }

                    //审核事件-通过
                    if ($eventype['event'] == "card_pass_check") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $WxCardHandle = new Wxcard();
                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['create_time'] = $pushdata['CreateTime'];
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['notpass'] = 1;
                        $WxCardHandle->cardpass($datas);
                        return "";

                    }
                    //审核事件-未通过
                    if ($eventype['event'] == "card_not_pass_check") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $WxCardHandle = new Wxcard();
                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['createtime'] = $pushdata['CreateTime'];
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['notpassinfo'] = $pushdata['RefuseReason'];
                        $datas['notpass'] = 0;
                        $WxCardHandle->cardpass($datas);
                        return "";

                    }

                    //领取事件
//                    $ActionLogs->writelog("payos", "wxauth", "event", "event-1:", $eventype['event']);
                    if ($eventype['event'] == "user_get_card") {

                        $pushdata = $weObj->getRev()->getRevData();
                        //END
                        $ActionLogs->writelog("payos", "wxauth", "event", "领取事件:", $pushdata);
                        $res = action('Wxcard/usergetcard', array($pushdata));
//                        $ActionLogs->writelog("payos", "wxauth", "event", "领取结束:", $res);
                        die("SUCCESS");
                    }

                    //转赠事件   但是领取事件包含了转赠方法
                    if ($eventype['event'] == "user_gifting_card") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $datas['openid'] = $pushdata['FromUserName'];
                        $datas['createtime'] = $pushdata['CreateTime'];
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['fromopenid'] = $pushdata['FriendUserName'];
                        $datas['usercardcode'] = $pushdata['UserCardCode'];
                        $datas['isgivecard'] = $pushdata['IsReturnBack'];
                        $datas['isChatRoom'] = $pushdata['ischatroom'];
                        return "";
                    }

                    //激活事件
                    if ($eventype['event'] == "submit_membercard_user_info") {

                        $pushdata = $weObj->getRev()->getRevData();
//                        file_put_contents('/data2/html/payos/exelog/fireuser/' . date("Y-m-d") . '.txt',  'fire-:' . json_encode($pushdata, JSON_UNESCAPED_UNICODE).PHP_EOL, FILE_APPEND);
                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['usercardcode'] = $pushdata['UserCardCode'];
                        $datas['openid'] = !empty($pushdata['FromUserName'])?$pushdata['FromUserName']:"";
                        $datas['createtime'] = $pushdata['CreateTime'];
                        action('Wxcard/userfirecard', array($datas));

                        return "";

                    }

                    //删除事件
                    if ($eventype['event'] == "user_del_card") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $datas['gh_id'] = !empty($pushdata['ToUserName'])?$pushdata['ToUserName']:"";

                        $datas['openid'] = !empty($pushdata['FromUserName'])?$pushdata['FromUserName']:"";
                        $datas['card_id'] = $pushdata['CardId'];
                        $datas['code'] = $pushdata['UserCardCode'];
                        $datas['create_time'] = $pushdata['CreateTime'];
                        action('Wxcard/userdelcard', array($datas));

                        return "";

                    }

                    //核销事件
                    if ($eventype['event'] == "user_consume_card") {
                        $pushdata = $weObj->getRev()->getRevData();

//                        $datas['openid'] = $pushdata['FromUserName'];
//                        $datas['cardid'] = $pushdata['CardId'];
//                        $datas['usercardcode'] = $pushdata['UserCardCode'];
//                        $datas['creattime'] = $pushdata['CreateTime'];
//                        $datas['consumesource'] = $pushdata['ConSumeSource'];
//                        $datas['locationname'] = $pushdata['LocationName'];
//                        $datas['staffopenid'] = $pushdata['StaffOpenid'];
//                        $datas['verifycode'] = $pushdata['VerifyCode'];
//                        $datas['remarkamount'] = $pushdata['RemarkAmount'];
//                        $datas['outerstr'] = $pushdata['OuterStr'];

                        action('Wxcard/userconsumecard', array($pushdata));
                        return "";


                    }

                    //买单事件推送
                    if ($eventype['event'] == "user_pay_from_pay_cell") {
                        $pushdata = $weObj->getRev()->getRevData();
                        return "success";

                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['openid'] = !empty($pushdata['FromUserName'])?$pushdata['FromUserName']:"";
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['usercardcode'] = $pushdata['UserCardCode'];
                        $datas['createtime'] = $pushdata['CreateTime'];
                        $datas['transid'] = $pushdata['TransId'];
                        $datas['locationid'] = $pushdata['LocationId'];
                        $datas['fee'] = $pushdata['Fee'];
                        $datas['originalfee'] = $pushdata['OriginalFee'];


                    }

                    //会员卡内容改变
                    if ($eventype['event'] == "update_member_card") {
                        $user = $weObj->getRevFrom();
                        $pushdata = $weObj->getRev()->getRevData();

                        $datas['openid'] = $user;
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['code'] = $pushdata['UserCardCode'];
                        $datas['creattime'] = $pushdata['CreateTime'];
                        $datas['modifybonus'] = $pushdata['ModifyBonus'];
                        $datas['modifybalance'] = $pushdata['ModifyBalance'];


                    }

                    //库存报警
                    if ($eventype['event'] == "card_sku_remind") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $datas['cardid'] = $pushdata['CardId'];
                        $datas['usercardcode'] = $pushdata['UserCardCode'];
                        $datas['createtime'] = $pushdata['CreateTime'];
                        $datas['detail'] = $pushdata['Detail'];
                        action('Wxcard/userskucard', array($datas));


                    }

                    //礼品卡支付
                    if ($eventype['event'] == "giftcard_pay_done") {
                        $pushdata = $weObj->getRev()->getRevData();
                        $datas['gh_id'] = $pushdata['ToUserName'];
                        $datas['openid'] = !empty($pushdata['FromUserName'])?$pushdata['FromUserName']:"";
                        $datas['create_time'] = $pushdata['CreateTime'];
                        $datas['page_id'] = $pushdata['PageId'];
                        $datas['orderid'] = $pushdata['OrderId'];
                        if (isset($pushdata['UnionId'])) {
                            $datas['unionid'] = $pushdata['UnionId'];
                        } else {
                            $datas['unionid'] = '';
                        }
                        $ActionLogs->writelog("payos", "wxauth", "event", "礼品卡支付事件:", $datas);

                        action('Wxcardgift/giftcardpay', array($datas));


                    }

//                    //小程序审核推送   （成功
//                    if ($eventype['event'] == "weapp_audit_success") {
//                        $pushdata = $weObj->getRev()->getRevData();
//                        action('Wxmicro/micropass', array($datas));
//                        exit();
//
//                    }
//                    //小程序审核推送   （失败
//                    if ($eventype['event'] == "weapp_audit_fail") {
//                        $pushdata = $weObj->getRev()->getRevData();
//                        action('Wxmicro/microadopt', array($datas));
//                        exit();
//
//                    }


                    break;

                case 'image':
                    //$weObj->text("hello, I'm wechat")->reply();

                    break;

                default:
                    $ActionLogs->writelog("payos", "wxauth", "event/def", "1:", $alldata);
                    break;

            }
        }
        }catch (\Exception $e){
            $postStr = file_get_contents('php://input');
            $msg = [];
            if (!empty($postStr)) {
                libxml_disable_entity_loader(true);
                $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            }
            $errdata['data'] = $msg;
            $errdata['error'] = $e->getMessage();
            file_put_contents('/data2/html/payos/lsztestlog01.log',date('Y-m-d H:i:s',time())."-".json_encode($errdata,JSON_UNESCAPED_UNICODE),8);
        }
    }

    //民生通知
    public function ms_api()
    {

        if ($_POST) {
            action('Cmmbpay/ms_orderquery', array($_POST['orderNo']));

            $su = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            echo $su;

        }


    }

    public function sendtemplate($id, $orderid)
    {

        $map['id'] = $id;
        $Merchant = new Merchant();
        $mach = $Merchant->where($map)->find();
        $mas['orderid'] = $orderid;
        $Paylog = new Paylog();
        $pay = $Paylog->where($mas)->field('mid,price,pay_fs,add_time,orderid,openid')->find();
        $Platurl = new Platurl();
        $options = $Platurl->getagenttplmsg($pay['mid']);
        $weObj = new Wxobjopen($options);
        $templateid = $Platurl->getagentpaytplid($pay['mid']);
        $Cashier = new MerchantCashier();

        $day = strtotime(date('Y-m-d'));
        $tom = strtotime(date('Y-m-d', strtotime('+1 day')));
        $mab['add_time'] = array(array('gt', $day), array('lt', $tom));
        $mab['mid'] = $id;
        $mab['pay_statu'] = 1;
        $sumday = $Paylog->where($mab)->sum('price');       //收款总计
        $wx['pay_fs'] = ['in', [0, 2]];
        $wxday = $Paylog->where($mab)->where($wx)->sum('price');       //微信
        $ali['pay_fs'] = ['in', [1, 3]];
        $aliday = $Paylog->where($mab)->where($ali)->sum('price');       //支付宝
        $xj['pay_fs'] = ['in', [4]];
        $xjday = $Paylog->where($mab)->where($xj)->sum('price');       //现金
        $card['pay_fs'] = ['in', [8]];
        $cardday = $Paylog->where($mab)->where($card)->sum('price');       //会员卡
        $mi['mid'] = $id;
        $mi['is_tz'] = 1;
        $touser = $Cashier->where($mi)->field('is_tz,openid')->select();
        $res = [];
        $templates = [];
        $touser['req_url'] = request()->url(true);
        $ActionLogs = new ActionLogs();
        $ActionLogs->writelog("payos", "wxauth", "send", "touser:", $touser);
        unset($touser['req_url']);
//        trace( "发送支付通知-用户：" . json_encode($touser,256),'SysRunNotifyLog');
        foreach ($touser as $v) {
            if ($v['is_tz'] == 1 && !empty($v['openid'])) {
                $template = array(
                    'touser' => $v['openid'],
                    'template_id' => $templateid,
                    'url' => '',
                    'topcolor' => "#7B68EE",
                    'data' => array(
                        'first' => array('value' => $mach['merchant'] . "收款提醒", 'color' => "#743A3A"),
                        'keyword1' => array('value' => $pay['price'] . "元", 'color' => '#FF0000'),
                        'keyword2' => array('value' => getpayfs($pay['pay_fs']), 'color' => '#000'),
                        'keyword3' => array('value' => date("Y-m-d H:i:s", $pay['add_time']), 'color' => '#000'),
                        'keyword4' => array('value' => $pay['orderid'], 'color' => '#000'),
                        'remark' => array('value' =>
                            "---------------------\n" .
                            "微 信  支 付:" . $wxday . "元\n" .
                            "支付宝支付:" . $aliday . "元\n" .
                            "现 金  支 付:" . $xjday . "元\n" .
                            "会员卡支付:" . $cardday . "元\n" .
                            "---------------------\n" .
                            "当日累计收款:" . $sumday . "元\n" .
                            "---------------------",
                            'color' => '#000'),
                    )
                );

                $res[] = $weObj->sendTemplateMessage($template);
                $templates[] = $template;
                $ActionLogs->writelog("payos", "wxauth", "send", "toinfo:", $template);
//                trace( "发送支付通知-通知内容：" . json_encode($template,256),'SysRunNotifyLog');
            }
        }
        $this->rec_paytpl_log($pay, $templates, $res, '', $templateid);
        return $res;

    }


    //添加发送记录
    private function rec_paytpl_log($order, $info, $res, $touser = '', $templateid)
    {
        $ActionLogs = new ActionLogs();
        try {
            $PayTplSend = new PayTplSend();
            $Platurl = new Platurl();
            $data['mid'] = $order['mid'];
            $data['openid'] = $order['openid'];
            $data['templateid'] = $templateid;
            $data['tpl_msg_type'] = $Platurl->getagenttplmsgtype($order['mid']);
            $data['orderid'] = $order['orderid'];
            $data['tpl_info'] = json_encode($info, JSON_UNESCAPED_UNICODE);
            $data['tpl_res'] = json_encode($res, JSON_UNESCAPED_UNICODE);
            $data['add_time'] = time();
            $ActionLogs->writelog("payos", "wxauth", "sendtemplate", "添加发送记录:", $data);
            $PayTplSend->allowField(true)->save($data);
        } catch (\Exception $e) {
            $data2 = array('code' => '9099', 'message' => $e->getMessage() . $e->getFile() . ":" . $e->getLine());
            $ActionLogs->writelog("payos", "wxauth", "sendtemplate", "添加发送记录错误:", $data2);
        }
    }


}